import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import tokenUtil from "@/core/util/tokenUtil.js";
import Swal from "sweetalert2";
import Router from "@/router.js";
import {handleNotify,handleAlert,showWating,closeWating} from "@/core/util/jehcUtil.js";
/**
 * Service to call HTTP request via Axios
 */
const apiUtil = {
  init() {
    // this.setHeader();//设置请求前增加header
    //请求数据拦截器
    axios.interceptors.request.use(request => {
      //全局显示加载进度条
      // showWating({});
      return request
    }, err => {
      return Promise.reject(err);
    });    
    
    //接收响应拦截器
    axios.interceptors.response.use(response => {
      // console.log("拦截器结果：",response.data.status);
      // handleNotify ('通知', '您的账号由于长时间没有操作已经失效', 'warning', 'top-right',  '3000');
      let requestStatus = response.status;
      if(requestStatus == 200){//请求状态码成功
          let status = response.data.status;
          //1.优先级判断访问成功后是否存在自定义非法信息提示
          if(status !== undefined){
            if(status==888){
                //1.session失效
                handleNotify ('通知', '您的账号由于长时间没有操作已经失效', 'warning', 'top-right',  '3000');
                setTimeout(function () {
                  // Router.push({ path: "/login" })
                  Router.push("/login" );
                  // this.$router.push('/login');
                  tokenUtil.destroyToken();
                }, 2000);
            }else if(status==777){
                //2.功能权限
                handleAlert("您还没有该模块的操作权限,请与管理员联系", "warning", 3)
            }else if(status==666){
                //3.非法页面
                handleAlert("您的请求访问，已经列入到黑名单中，我们建议您联系管理员，谢谢！", "warning", 3)
            }else if(status == 500){
                  Swal.fire({
                    text:response.data.message,
                    icon: "error",
                    buttonsStyling: false,
                    confirmButtonText: "请重新试一下!",
                    customClass: {
                      confirmButton: "btn fw-bold btn-light-danger",
                    }
                  });
            }
        }
      }    
      closeWating();//关闭进度条
      return response
    }, err => {      
      closeWating();//关闭进度条
      if (err && err.response) {
        switch (err.response.status) {
          case 400: err.message = '请求错误(400)'; break;
          case 401: Router.push("/login" ); break;
          case 403: err.message = '拒绝访问(403)'; break;
          case 404: err.message = '请求出错(404)'; break;
          case 408: err.message = '请求超时(408)'; break;
          case 500: err.message = '服务器错误(500)'; break;
          case 501: err.message = '服务未实现(501)'; break;
          case 502: err.message = '网络错误(502)'; break;
          case 503: err.message = '服务不可用(503)'; break;
          case 504: err.message = '网络超时(504)'; break;
          case 505: err.message = 'HTTP版本不受支持(505)'; break;
          default: err.message = `连接出错(${err.response.status})!`;
        }
      } else {
        err.message = '连接服务器失败!'
      }
      message.error(err.message);
      handleAlert(err.message, "error", 3)
      return Promise.reject(err);
    });
  },
  
  /**
   * Set the default HTTP request headers
   */
  setHeader() {
    let token = `${tokenUtil.getToken()}`;
    let JEHC_SESSION_ID = `${tokenUtil.getJSessionId()}`;
    if(token===undefined ||token==="undefined"){
      token = "";
    }    
    if(JEHC_SESSION_ID===undefined||JEHC_SESSION_ID==='undefined'||JEHC_SESSION_ID==="null"||JEHC_SESSION_ID===null){
      JEHC_SESSION_ID = "";
    }    
    axios.defaults.headers["token"] = token;
    axios.defaults.headers["JEHC-SESSION-ID"] = JEHC_SESSION_ID;
  },

  /**
   * 分页查询（post方式查询）
   * @param {*} resource 
   * @param {*} params 
   * @returns 
   */
  queryPage(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.post(resource, params).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * get方式查询
   * @param {*} resource 
   * @param {*} params 
   * @returns 
   */
  query(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.get(`${resource}`, {params:params}).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * Send the GET HTTP request
   * @param resource
   * @param slug
   * @returns {*}
   */
  get(resource, slug = "") {
    this.setHeader();//设置请求前增加header
    return axios.get(`${resource}/${slug}`).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  

  /**
   * Send the GET HTTP request
   * @param resource
   * @param slug
   * @returns {*}
   */
  get(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.get(`${resource}`, {params:params}).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  // /**
  //  * Send the GET HTTP request
  //  * @param resource
  //  * @param params
  //  * @returns {*}
  //  */
  // get(resource, params) {
  //   // this.setHeader();//设置请求前增加header
  //   return axios.get(resource, params).catch(error => {
  //     // console.log(error);
  //     throw new Error(`[KT] apiUtil ${error}`);
  //   });
  // },

  /**
   * Set the POST HTTP request
   * @param resource
   * @param params
   * @returns {*}
   */
  post(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.post(`${resource}`, params).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * Send the UPDATE HTTP request
   * @param resource
   * @param slug
   * @param params
   * @returns {IDBRequest<IDBValidKey> | Promise<void>}
   */
  update(resource, slug, params) {
    this.setHeader();//设置请求前增加header
    return axios.put(`${resource}/${slug}`, params).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * Send the UPDATE HTTP request
   * @param resource
   * @param params
   * @returns {IDBRequest<IDBValidKey> | Promise<void>}
   */
  update(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.put(`${resource}`, params).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * Send the PUT HTTP request
   * @param resource
   * @param params
   * @returns {IDBRequest<IDBValidKey> | Promise<void>}
   */
  put(resource, params) {
    this.setHeader();//设置请求前增加header
    return axios.put(`${resource}`, params).catch(error => {
      // console.log(error);
      // throw new Error(`[KT] apiUtil ${error}`);
    });
  },

  /**
   * Send the DELETE HTTP request
   * @param resource
   * @returns {*}
   */
  delete(resource) {
    this.setHeader();//设置请求前增加header
    return axios.delete(resource).catch(error => {
      // console.log(error);
      // throw new Error(`[RWV] apiUtil ${error}`);
    });
  },

  /**
   * Send the DELETE HTTP request
   * @param resource
   * @returns {*}
   */
  delete(resource,params) {
    this.setHeader();//设置请求前增加header
    return axios.delete(`${resource}`, {params:params}).catch(error => {
      // console.log(error);
      // throw new Error(`[RWV] apiUtil ${error}`);
    });
  }
};
export default apiUtil;
